// ==UserScript==
// @name         alist auto retry
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *://yonghome.dynv6.net:15244/*
// @require      https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js
// @grant        GM_info
// @grant        GM_download
// @grant        GM_openInTab
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    const alistHelper={};
    alistHelper.addAutoRetry = function() {
        let base = $(".hope-stack .hope-c-PJLV-ihVlqVC-css");
        if (base.length == 0) {
            return;
        }
        const ele = '<button id="jsretry" class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-subtle hope-c-ivMHWx-kWSPeQ-size-md hope-c-ivMHWx-dMllzy-cv hope-c-PJLV hope-c-PJLV-iikaotv-css" type="button" role="button">全部重试</button>';
        base.append(ele);
        clearInterval(alistHelper.timer);
        alistHelper.buttonText = $('#jsretry').text();
        $('#jsretry').click(function() {
            alistHelper.loadFailTask();
	    });
    };
    alistHelper.loadFailTask = function() {
        if (alistHelper.taskList && (alistHelper.taskListIndex<alistHelper.taskList.length)){
            return;
        }
        GM_xmlhttpRequest({
            url:'/api/admin/task/copy/done',
            method: "get",
            headers: {
                "Authorization": localStorage.getItem('token'),
            },
            onload: function(response) {
                let status = response.status;
                if(status==200||status=='200'){
                    let data = JSON.parse(response.response)
                    if (data.code != 200) {
                        console.log(data);
                        alert('接口调用失败');
                        return;
                    }
                    alistHelper.taskList = data.data;
                    alistHelper.taskListIndex = 0;
                    if (data.data) {
                        alistHelper.timer = setInterval(alistHelper.retryAllTask, 1000);
                        $('#jsretry').text(alistHelper.buttonText+ `${alistHelper.taskListIndex}/${alistHelper.taskList.length}`);
                    }
                }
            }
        });
    };
    alistHelper.retryAllTask = function() {
        for (let i=alistHelper.taskListIndex;i<alistHelper.taskList.length;++i) {
            let data = alistHelper.taskList[i];
            if (data.state != 'errored') {
                continue;
            }
            alistHelper.retryTask(data.id);
            alistHelper.taskListIndex = (i+1);
            break;
        }
        $('#jsretry').text(alistHelper.buttonText+ `${alistHelper.taskListIndex}/${alistHelper.taskList.length}`);
        if (alistHelper.taskList.length <= alistHelper.taskListIndex) {
            clearInterval(alistHelper.timer);
            alert("全部重试完成");
        }
    };
    alistHelper.retryTask = function(id) {
        GM_xmlhttpRequest({
            url:'/api/admin/task/copy/retry?tid='+id,
            method: "post",
            headers: {
                "Authorization": localStorage.getItem('token'),
            },
            onload: function(response) {
                let status = response.status;
                let data = JSON.parse(response.response)
                if(!((status==200||status=='200')&&data.code == 200)){
                    console.log(id, 'retry failed');
                }
            }
        });
    };
    // -------------------------------------------------------------------------------------------------------------
    alistHelper.addCompareBtn = function() {
        let base = $("nav");
        if (base.length == 0) {
            return;
        }
        const btnSrc = '<button class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-solid hope-c-ivMHWx-dwWzpk-size-sm hope-c-ivMHWx-IjcEH-size-md hope-c-ivMHWx-EevEv-cv hope-c-PJLV hope-c-PJLV-ihbZbLe-css"'+
              ' type="button" role="button" id="jsCmpSrc">设置比较源</button>'
        const btnDst = '<button class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-solid hope-c-ivMHWx-dwWzpk-size-sm hope-c-ivMHWx-IjcEH-size-md hope-c-ivMHWx-EevEv-cv hope-c-PJLV hope-c-PJLV-ihbZbLe-css"'+
              'type="button" role="button" id="jsCmpDst">开始比较</button>'
        console.log('test', alistHelper.compareSrc);
        if (alistHelper.compareSrc === undefined) {
            base.children(1).append(btnSrc);
        } else {
            base.children(1).append(btnDst);
        }
        clearInterval(alistHelper.timer);
        $('#jsCmpSrc').click(function() {
            alistHelper.compareSrc = decodeURI(window.location.pathname);
            $('#jsCmpSrc').remove();
            console.log(alistHelper.compareSrc)
            base.children(1).append(btnDst);
            $('#jsCmpDst').click(function() {
                $('#jsCmpDst').remove();
                alistHelper.addCompareBtn();
                alistHelper.doCompare(alistHelper.compareSrc, decodeURI(window.location.pathname));
            });
	    });
    };
    alistHelper.doCompare = function(src, dst) {
        let data = {'src':src, 'dst':dst, fileList:[]};
        alistHelper.listAll(src, data);
        alistHelper.listAll(dst, data);
    };
    alistHelper.compareFiles = function(files) {
        if (!(files[files.src] && files[files.dst])){
            return
        }
        let src = files['src']
        let dst = files['dst']
        let fileList = files.fileList
        let objs = {}
        for (let obj of files[dst].content) {
            objs[obj.name] = obj
        }
        for (let obj of files[src].content) {
            if (objs[obj.name] == undefined || objs[obj.name].size != obj.size) {
                if (obj.is_dir) {
                    alistHelper.mkdir(dst + '/' + obj.name)
                } else {
                    obj.pathDst = dst
                    obj.pathSrc = src
                    if (fileList.length == 0) {
                        obj.totalSize = obj.size
                    } else {
                        fileList[0].totalSize = fileList[0].totalSize + obj.size
                    }
                    fileList.push(obj)
                    //if (fileList.length >= count || (fileList.length > 0 && fileList[0].totalSize > 50*1024*1024*1024)) {
                    //    return
                    //}
                }
            }
        }
        for (let obj of files[src].content) {
            if (obj.is_dir) {
                alistHelper.doCompare(src+'/'+obj.name, dst+'/'+obj.name)
            }
        }
        alistHelper.copyTask(src, dst, fileList)
    };
    alistHelper.listAll = function(path, files) {
        let data = {
            page: 1,
            password:"",
            path:path,
            per_page:0,
            refresh:false
        };
        alistHelper.makeRequest('/api/fs/list', 'post', data, function (rsp,status) {
            files[path] = rsp.data
            alistHelper.compareFiles(files)
        });
    };
    alistHelper.makeRequest = function(url, method, data, callback) {
        $.ajax({
          url: url,
          data: JSON.stringify(data),
          contentType: "application/json",
          type: method,
          beforeSend: function(request) {
            request.setRequestHeader("Authorization",localStorage.getItem('token'));
          },
          success: callback
        });
    };
    alistHelper.mkdir = function(path) {
        let data = {path: path}
        return alistHelper.makeRequest('/api/fs/mkdir', 'post', data, function (rsp,status) {
        })
    };
    alistHelper.copyTask = function(src, dst, fileList) {
        if (!fileList || fileList.length <=0) return
         let data = {
            "src_dir": src,
            "dst_dir": dst,
            "names": []
        }
        for (let obj of fileList) {
            data.names.push(obj.name)
        }
        return alistHelper.makeRequest('/api/fs/copy', 'post', data, function (rsp,status) {
        })
    };
    if (window.location.pathname.indexOf('@manage') > 0) {
        if (window.location.pathname.indexOf('tasks/copy') > 0) {
            alistHelper.timer = setInterval(alistHelper.addAutoRetry, 1000);
        }
    } else {
       alistHelper.timer = setInterval(alistHelper.addCompareBtn, 1000);
    }
})();